from django.utils.translation import ugettext as _
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist

from tagging.models import Tag, TaggedItem
from tagging.utils import get_tag, get_queryset_and_model

def tagged_objects(content_type = None, tag = None, related_tags = False, related_tag_counts = True, **kwargs):
    if content_type is None:
        raise AttributeError(_('tagged_objects must be called with a content type'))
    else:
        try:
            model_content_type = ContentType.objects.get(id = int(content_type))
        except ObjectDoesNotExist:
            raise AttributeError(_('tagged_objects must be called with a valid content type'))

    if tag is None:
        raise AttributeError(_('tagged_objects must be called with a tag.'))
    
    tag_instance = get_tag(tag)
    if tag_instance is None:
        raise AttributeError(_('tagged_object must be called with a valid tag'))
    
    queryset = TaggedItem.objects.get_by_model(model_content_type.model_class(), tag_instance)
    if related_tags:
        related_tags_list = \
            Tag.objects.related_for_model(tag_instance, queryset_or_model, counts=related_tag_counts)
    else:
        related_tags_list = None
        
    return queryset, related_tags_list